<?php
/**
 * User: zhangligang
 * Email: tzhang2450@163.com
 * Date: 2018/11/20
 * Time: 03:11
 */

namespace App\Http\Services;


use App\Http\Models\Category;
use Symfony\Component\Finder\Exception\AccessDeniedException;

class CategoryService
{

    public static function categories()
    {
        $categories = Category::where('is_del', 0)->get();
        $data = [];
        foreach ($categories as $category) {
            $data[] = [
                'id' => $category->id,
                'name' => $category->name
            ];
        }
        return $data;
    }

    public static function getList($limit, $offset, $order = 'desc')
    {
        $query = Category::where('is_del', 0);
        $total = $query->count();
        $categories = $query->orderBy('id', $order)->limit($limit)->offset($offset)->get();
        $data = [];
        foreach ($categories as $category) {
            $data[] = [
                'id' => $category->id,
                'name' => $category->name,
                'created_at' => date('Y-m-d', strtotime($category->created_at))
            ];
        }

        return [
            'total' => $total,
            'rows' => $data,
            'page_size' => $limit,
            'offset' => $offset,
            'pages' => ceil($total / $limit),
            'page_number' => $offset / $limit + 1
        ];
    }

    public static function getById($id)
    {
        $category = Category::where('id', $id)->where('is_del', 0)->first();

        if (!$category) {
            return [];
        }

        return [
            'id' => $category->id,
            'name' =>$category->name
        ];
    }

    public static function save($data)
    {
        $now = date('Y-m-d H:i:s', time());
        if (array_key_exists('id', $data)) {
            $category = Category::where('id', $data['id'])->where('is_del', 0)->first();
            if (!$category) {
                throw new AccessDeniedException('作品分类不存在或已删除', 4032);
            }
        } else {
            $category = new Category();
            $category->is_del = 0;
            $category->created_at = $now;
        }

        $category->name = $data['name'];
        $category->updated_at = $now;
        $category->save();
    }

    public static function delete($id)
    {
        $category = Category::where('id', $id)->where('is_del', 0)->first();
        if (!$category) {
            throw new AccessDeniedException('作品分类不存在或已删除', 4032);
        }
        $category->is_del = 1;
        $category->updated_at = date('Y-m-d H:i:s', time());
        $category->save();
    }
}